package com.cn.wolf.nio.groupchat;

import com.cn.wolf.common.Constants;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.Iterator;

/**
 * @author huangy 群聊服务端
 * @since 2022/11/27 11:30 上午
 */
public class GroupChatServer {

    //选择器
    private static Selector selector;

    //服务端通道
    private static ServerSocketChannel listenChannel;

    public GroupChatServer() {
        try {
            selector = Selector.open();
            listenChannel = ServerSocketChannel.open();
            //绑定对应的端口
            listenChannel.bind(new InetSocketAddress(Constants.PORT));
            //设置非阻塞模式
            listenChannel.configureBlocking(false);
            //将listenChannel注册到selector中 并关注连接事件
            listenChannel.register(selector, SelectionKey.OP_ACCEPT);
            System.out.println("初始化成功");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 监听
     *
     * @author huangy
     * @since 2022/11/27 11:57 上午
     **/
    @SuppressWarnings("all")
    public void listen() {
        try {
            while (true) {
                int count = selector.select();
                if (count > 0) {
                    Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
                    while (iterator.hasNext()) {
                        SelectionKey key = iterator.next();
                        //监听accept
                        if (key.isAcceptable()) {
                            SocketChannel sc = listenChannel.accept();
                            sc.configureBlocking(false);
                            //将socketChannel注册到selector上
                            sc.register(selector, SelectionKey.OP_READ);
                            //提示连接信息
                            System.out.println(sc.getRemoteAddress() + " 上线 ");
                        }
                        //监听可读事件
                        if (key.isReadable()) {
                            readData(key);
                        }
                        //将key移除避免重复处理
                        iterator.remove();
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 读取数据
     *
     * @param key 读取通道
     * @author huangy
     * @since 2022/11/27 2:46 下午
     **/
    private void readData(SelectionKey key) {
        //取得关联的channel
        SocketChannel channel = null;
        try {
            channel = (SocketChannel) key.channel();
            ByteBuffer buffer = ByteBuffer.allocate(1024);
            int read = channel.read(buffer);
            if (read > 0) {
                String msg = new String(buffer.array());
                System.out.println("来自客户端消息: " + msg);
                //将收到的消息转发给其他客户端
                sendMsg2OtherClients(msg, channel);
            }
        } catch (IOException e) {
            try {
                System.out.println(channel.getRemoteAddress() + " 离线 ");
                //取消注册
                key.channel();
                //关闭通道
                channel.close();
            } catch (IOException ioException) {
                ioException.printStackTrace();
            }
            e.printStackTrace();
        }
    }

    /**
     * 转发消息给其他客户端
     *
     * @param msg  消息内容
     * @param self 自身
     * @author huangy
     * @since 2022/11/27 3:00 下午
     **/
    public void sendMsg2OtherClients(String msg, SocketChannel self) throws IOException {
        System.out.println("服务器转发消息中");
        //转发给所有注册到selector的socketChannel 并排除self
        for (SelectionKey key : selector.keys()) {
            Channel channel = key.channel();
            if (channel instanceof SocketChannel && !channel.equals(self)) {
                SocketChannel target = (SocketChannel) channel;
                ByteBuffer buffer = ByteBuffer.wrap(msg.getBytes());
                target.write(buffer);
            }
        }
    }

    public static void main(String[] args) {
        GroupChatServer chatServer = new GroupChatServer();
        chatServer.listen();
    }

}
